<?php
/**
 * Pes for PHP 5.3+
 *
 * Copyright (c) 2013 phpeskill.com (http://www.phperskill.com)
 *
 * For the full copyright and license information, please view
 * the file LICENSE.md that was distributed with this source code.
 */
namespace Model\Admin;

/**
 * Pes 后台菜单模型
 * @author LazyPHP
 * @version 1.0
 */
class MenuModel extends CommonModel {
    
    /**
     * 获取后台菜单
     * @return json 返回json格式的菜单
     */
    public static function getMenu(){
        $db = self::db('menu');
        $result = $db->order('listsort desc, id asc')->select();
        $menu = self::traversalMenu($result);
        return json_encode($menu);
    }
    
    /**
     * 遍历排序菜单
     * @param array $menuArray 菜单数组
     * @return array 返回遍历排序过的菜单
     */
    private static function traversalMenu(array $menuArray){
            foreach($menuArray as $key => $value){
                if($value['parent'] == 'root'){
                    $menu[$value['value']] = array(
                                                'id' => $value['value'],
                                                'name' => $value['name'],
                                                'icon' => '',
                                                'menuId' => $value['id'],
                                                'tip' => $value['name'],
                                                'parent' => $value['parent'],
                                                'top' => '',
                                                'items' => array()
                                             ); 
                }
            }
            foreach ($menuArray as $key => $value){
                if($value['parent'] == $menu[$value['parent']]['id']){
                    $menu[$value['parent']]['items'][$value['value']] =
                                                array('id' => $value['value'],
                                                'name' => $value['name'],
                                                'icon' => '',
                                                'menuId' => $value['id'],
                                                'tip' => $value['name'],
                                                'parent' => $value['parent'],
                                                'top' => '',
                                                'url' => $value['url']
                                                );
                }
            }
        return $menu;
    }
    
    public static function topMenu(){
        $db = self::db('menu');
        $topMenu = $db->where('parent = "root"')->select();
        return $topMenu;
    }

}